// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import './shortcut_input.js';

import {I18nMixinLit} from 'chrome://resources/cr_elements/i18n_mixin_lit.js';
import {CrLitElement} from 'chrome://resources/lit/v3_0/lit.rollup.js';

import type {KeyboardShortcutDelegate} from './keyboard_shortcut_delegate.js';
import {createDummyKeyboardShortcutDelegate} from './keyboard_shortcut_delegate.js';
import {getCss} from './keyboard_shortcuts.css.js';
import {getHtml} from './keyboard_shortcuts.html.js';

const ExtensionsKeyboardShortcutsElementBase = I18nMixinLit(CrLitElement);

// The UI to display and manage keyboard shortcuts set for extension commands.
export class ExtensionsKeyboardShortcutsElement extends
    ExtensionsKeyboardShortcutsElementBase {
  static get is() {
    return 'extensions-keyboard-shortcuts';
  }

  static override get styles() {
    return getCss();
  }

  override render() {
    return getHtml.bind(this)();
  }

  static override get properties() {
    return {
      delegate: {type: Object},
      items: {type: Array},
    };
  }

  delegate: KeyboardShortcutDelegate = createDummyKeyboardShortcutDelegate();
  items: chrome.developerPrivate.ExtensionInfo[] = [];

  override firstUpdated() {
    this.addEventListener('view-enter-start', this.onViewEnter_);
  }

  private onViewEnter_() {
    chrome.metricsPrivate.recordUserAction('Options_ExtensionCommands');
  }

  protected calculateShownItems_(): chrome.developerPrivate.ExtensionInfo[] {
    return this.items.filter(function(item) {
      return item.commands.length > 0;
    });
  }

  protected computeScopeAriaLabel_(
      item: chrome.developerPrivate.ExtensionInfo,
      command: chrome.developerPrivate.Command): string {
    return this.i18n('shortcutScopeLabel', command.description, item.name);
  }

  /**
   * Determines whether to disable the dropdown menu for the command's scope.
   */
  protected computeScopeDisabled_(command: chrome.developerPrivate.Command):
      boolean {
    return command.isExtensionAction || !command.isActive;
  }

  protected onScopeChanged_(event: Event) {
    const target = event.target as HTMLSelectElement;
    const extensionId = target.dataset['extensionId']!;
    const commandName = target.dataset['commandName']!;
    this.delegate.updateExtensionCommandScope(
        extensionId, commandName,
        (target.value as chrome.developerPrivate.CommandScope));
  }
}

// Exported to be used in the autogenerated Lit template file
export type KeyboardShortcutsElement = ExtensionsKeyboardShortcutsElement;

declare global {
  interface HTMLElementTagNameMap {
    'extensions-keyboard-shortcuts': ExtensionsKeyboardShortcutsElement;
  }
}

customElements.define(
    ExtensionsKeyboardShortcutsElement.is, ExtensionsKeyboardShortcutsElement);
